<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/impoet')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop:'timeOfEntry',order:'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100px;height:100px">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ hireTypeFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template>
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}s`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <empDialog ref="empDialog" @close="showDialog=false" @success="hSuccess" />
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="roleShowDialog" />
      <AssignRole v-if="roleShowDialog" :role-id="roleId" @close="roleShowDialog=false" />
    </div>
  </div>
</template>
<script>
import AssignRole from './assignRole.vue'
import { getEmployees, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import empDialog from './empDialog.vue'
console.log('employeesEnum', employeesEnum.hireType)
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    empDialog,
    AssignRole
  },
  data() {
    return {
      roleId: '',
      roleShowDialog: false, // 控制分配角色对话框的显示和隐藏
      showDialog: false, // 控制新增员工对话框的显示和隐藏
      list: [],
      page: 1,
      size: 2,
      total: 0
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hAssignRole(id) {
      this.roleId = id
      this.roleShowDialog = true
    },
    dataFormat(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      let headers = []
      if (one) {
        // console.log('Object.keys(one)', Object.keys(one))
        headers = Object.keys(one).map(enkey => {
          return mapInfo[enkey]
        })
      }
      const data = list.map(item => {
        return Object.values(item)
      })
      return { headers, data }
    },
    async handleDownload() {
      try {
        const res = await getEmployees(this.page, this.size)
        if (res.code !== 10000) return
        console.log(res.data.rows, 'res.data.rows')
        const { headers, data } = this.dataFormat(res.data.rows)
        //  import('@/vendor/Export2Excel')  懒加载的方式读取一个文件（模块）返回是一个promise实例对象
        import('@/vendor/Export2Excel').then(excel => {
        // excel指的是模块对象(文件对象)，就可以直接调用文件中的任何函数或者使用文件中的任何变量  excel.函数名()   || excel.变量
          console.log(excel, 'excel')
          // const tHeader = ['姓名', '年龄']
          // const data = [['曹操', 40], ['刘备', 45]]
          //  excel调用export_json_to_excel()
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 实现删除
    hDel(id) {
      this.$confirm('确定删除').then(
        async() => {
          const res = await delEmployee(id)
          console.log('delEmployee', res)
          // 处理删除的特殊情况 当页面只有一条数据的时候 让page减1
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadEmployees()
        }
      ).catch(err => err)
    },
    // 重置表单
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    // 新增员工渲染关闭弹层
    hSuccess() {
      // 获取最大页码值
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 返回正式或非正式
    hireTypeFormat(data) {
      // return employeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 加载员工列表
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size)
        if (res.code === 10000) {
          this.list = res.data.rows
          this.total = res.data.total
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
